/*
 * @Description:
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-11-18 11:19:31
 * @LastEditors: kafei
 * @LastEditTime: 2021-12-15 17:24:36
 */
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/token' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect', '/vue'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  console.log('asdww', to, to.path.includes('/sub02'))
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/dashboard' })
      NProgress.done()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        console.log('asdasdaszzzzz')
        next()
      } else {
        try {
          const { rid } = await store.dispatch('user/GET_USERINFO')
          await store.dispatch('user/GET_MENU_ByRole', rid)
          store.commit('user/SET_MENU_TOROUTES')
          console.log(store.getters.routes, 'store.getters.routes')
          router.addRoutes(store.getters.routes)
          if (to.redirectedFrom) {
            router.replace(to.redirectedFrom)
          } else {
            next({
              ...to,
              replace: true
            })
          }
          next({ ...to, replace: true })
        } catch (error) {
          Message.error(error || 'Has Error')
          next('/login')
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
